import time

import yaml
from selenium import webdriver


class TestGetCookies:
    def setup(self):
        # 实例化driver 复用浏览器
        # chrome --remote-debugging-port=9222
        opt = webdriver.ChromeOptions()
        opt.debugger_address = '127.0.0.1:9222'
        self.driver = webdriver.Chrome(options=opt)
        # 设置隐式等待 找不到的话最多等5秒
        self.driver.implicitly_wait(10)
        # 打开网页
        self.driver.get('https://work.weixin.qq.com/wework_admin/frame')

    def test_get_cookie(self):
        cookies = self.driver.get_cookies()
        with open("D:/Study/git/WeComWebTest/data/cookies.yaml", "w", encoding="utf-8") as f:
            yaml.dump(cookies, f)

    def test_add_cookie(self):
        # 1. 访问企业微信主页面
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame#contacts")
        # 2. 定义cookie，cookie信息从已经写入的cookie文件中获取
        cookie = yaml.safe_load(open("D:/Study/git/WeComWebTest/data/cookies.yaml"))
        # 3. 植入cookie
        for c in cookie:
            self.driver.add_cookie(c)
        time.sleep(3)
        # 4.再次访问企业微信页面，发现无需扫码自动登录，而且可以多次使用
        self.driver.get("https://work.weixin.qq.com/wework_admin/frame#contacts")